from rest_framework import serializers

from .models import Category, News


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__'

class NewsSerializer(serializers.ModelSerializer):
    #重写 create 和update方法，加工字段
    def create(self, validated_data):
        print(validated_data)
        return super().create(validated_data)

    def update(self, instance, validated_data):
        print(instance)
        print(validated_data)
        return super().update(instance, validated_data)

    class Meta:
        model = News
        fields = '__all__'
        depth = 1  # 序列化深度depth属性能够将关联属性的表属性也显示序列化出来

class NewsGetSerializer(serializers.ModelSerializer):
    # 多对一查询
    category = CategorySerializer()
    class Meta:
        model = News
        fields = '__all__'

class CategoryGetSerializer(serializers.ModelSerializer):
    # 一对多查询
    news = NewsSerializer(read_only=True, many=True)
    class Meta:
        model = Category
        fields = '__all__'